<!-- 文本列表 -->
<template>
  <a-spin wrapper-class-name="spin-wrapper-class-name" :spinning="loading || getUserHistoryLoading || getTaskTextListLoading">
    <div class="text-list">
      <div class="flex-shrink-0">
        <title-bar title="文本列表" />
      </div>
      <div class="search-wrap">
        <index-filter v-model:value="indexValue" @reset="indexFilterReset" @inquire="indexFilterInquire" />
        <a-select
          v-model:value="typeSelected"
          :options="selectOption"
          size="small"
          class="index-filter-select-wrap"
          style="width: 132px"
          @change="onSelectChange"
        />
      </div>
      <ul class="text-list-wrap my-scrollbar">
        <!-- <a-checkbox-group v-model:value="checkboxList" style="width: 100%"> -->
        <li
          v-for="(item, index) in dataList"
          :key="index"
          class="text-list-item"
          :class="item.id === currentId && 'active'"
          @click.stop="selectText(item)"
        >
          <!-- <div class="checkbox-wrap">
            <a-checkbox :disabled="!isEditable" :value="item.id" @click.stop="" />
          </div> -->
          <div class="w-56 pl-16 elliptical-1 text-list-item-index">{{ item?.num }}</div>
          <!-- <div class="w-16 label-status" :class="item.markType === 1 && 'marked'">
          <i class="iconfont icon-flag-fill"></i>
        </div> -->
          <div class="text-list-item-content" :class="item.remove === 1 && 'delete'" :title="item.text">{{ item.text }}</div>
        </li>
        <!-- </a-checkbox-group> -->
        <my-infinite-loading
          :first-load="false"
          :empty="dataList.length === 0"
          img-margin-top="120px"
          :identifier="identifier"
          @infinite="loadData"
        />
      </ul>
    </div>
  </a-spin>
  <transition>
    <div v-if="checkboxList.length" class="footer">
      <div class="deselect-all" @click="uncheck">取消选中</div>
      <div class="number-of-selected">已选{{ checkboxList.length }}条</div>
      <div v-if="checkPermissions(dataSetDetail?.createType, dataSetDetail?.readOnly)" class="batch-deletion" @click="batchDeletionOfIDs">
        批量删除
      </div>
    </div>
  </transition>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { onMounted, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRoute } from 'vue-router'

  import { textLabelApi } from '@/services/api'
  import { checkPermissions } from '@/utils/share'

  import IndexFilter, { IndexFilterValue } from '../../components/IndexFilter.vue'
  import TitleBar from '../../components/TitleBar.vue'

  export interface TextListProps {
    currentId: string
    selected?: number
    loading?: boolean
    indexValueList?: IndexFilterValue
  }

  withDefaults(defineProps<TextListProps>(), {
    currentId: '',
    selected: 0,
    loading: false,
    indexValueList: () => [undefined, undefined]
  })

  const emits = defineEmits<{
    (event: 'selectedText', data: any): void
    (event: 'update:selected', data: any): void
    (event: 'update:indexValueList', data: IndexFilterValue): void
    (event: 'batchDelete', data: string[]): void
  }>()

  export interface PageFormType {
    columns?: string
    limit: number
    taskId?: string
    numStart?: number
    numEnd?: number
    offset: number
    order?: string
  }

  // 是否可编辑
  // const isEditable = inject<Ref<boolean>>('isEditable') || ref(true)

  const route = useRoute()
  const pageParams = route.params

  const dataSetDetail = ref<any>({})

  const checkboxList = ref<string[]>([])

  // 文本筛选
  const indexValue = ref<IndexFilterValue>([undefined, undefined])
  const typeSelected = ref<number>(0)
  const selectOption = [
    { label: '未标注', value: 0 },
    { label: '已标注', value: 1 },
    { label: '无效', value: 2 }
  ]

  // 查询索引
  const indexFilterInquire = () => {
    emits('update:indexValueList', indexValue.value)
    emits('update:selected', typeSelected.value)
    refreshList()
  }

  // 重置索引
  const indexFilterReset = async () => {
    const { data } = await textLabelApi.resetUserHistory({ taskId: pageParams?.id, type: typeSelected?.value })
    const startNum = data.numStart || undefined
    const numEnd = data.numEnd || undefined
    indexValue.value = [startNum, numEnd]
    emits('update:indexValueList', indexValue.value)
    refreshList()
  }

  // 改变下拉框
  const onSelectChange = () => {
    emits('update:selected', typeSelected.value)
    refreshList()
  }

  const pageForm = ref<PageFormType>({
    limit: 20,
    taskId: pageParams?.id as string,
    offset: 1
  })
  const dataList = ref<any[]>([])
  const identifier = ref<number>(1)
  const { loading: getTaskTextListLoading, runAsync: runGetTaskTextList } = useRequest<any>(textLabelApi.getTaskTextList)
  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = await runGetTaskTextList({
        type: typeSelected.value,
        numStart: indexValue.value?.[0],
        numEnd: indexValue.value?.[1],
        ...pageForm.value
      })
      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }
      dataList.value.push(...records)
    } catch (error) {
      $state.error()
    }
  }

  // 获取当前用户历史操作信息
  const { loading: getUserHistoryLoading, runAsync: runGetUserHistory } = useRequest<any>(textLabelApi.getUserHistory)
  const getUserHistory = async () => {
    const { data } = await runGetUserHistory({}, { urlParams: { id: pageParams?.id } })
    const startNum = data.numStart || undefined
    const numEnd = data.numEnd || undefined
    const type = data.type ?? 0
    indexValue.value = [startNum, numEnd]
    typeSelected.value = type
    emits('update:selected', typeSelected.value)
    refreshList()
  }

  // 刷新列表
  const refreshList = (params?: Partial<PageFormType>) => {
    Object.assign(pageForm.value, { ...params, offset: 1 })
    dataList.value = []
    identifier.value = Date.now()
    uncheck()
  }

  // 当前点击
  const selectText = (item: any) => {
    emits('selectedText', item)
  }

  // 取消选中
  const uncheck = () => {
    checkboxList.value = []
  }

  // 批量删除
  const batchDeletionOfIDs = async () => {
    await textLabelApi?.delAllText(
      {},
      {
        data: {
          idList: checkboxList.value
        },
        isAddUid: true
      }
    )

    emits('batchDelete', checkboxList.value)
    message.success('删除成功')
    checkboxList.value = []
    refreshList()
  }

  // 单个删除
  const delText = async (id: string) => {
    await textLabelApi?.delText({}, { urlParams: { id } })
    message.success('删除成功')
    refreshList()
  }

  onMounted(() => {
    getUserHistory()
  })

  defineExpose({
    refreshList,
    delText
  })
</script>

<style lang="less" scoped>
  .text-list {
    display: flex;
    width: 100%;
    min-width: 0;
    height: 100%;
    min-height: 0;
    flex-direction: column;

    .search-wrap {
      display: flex;
      padding: 0 24px;
      width: 100%;
      height: 40px;
      border-bottom: 1px solid @mask1;
      flex-shrink: 0;
      gap: 0 8px;
    }

    .text-list-wrap {
      overflow-y: auto;
      padding: 0 8px;
      width: 100%;
      flex: 1;

      .text-list-item {
        display: flex;
        align-items: center;
        width: 100%;
        min-width: 0;
        height: 54px;
        border-bottom: 1px solid @border1;
        cursor: pointer;

        &.active {
          background: rgba(24, 104, 233, 0.08);
        }

        > div {
          flex-shrink: 0;
        }

        .checkbox-wrap {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 48px;
          height: 100%;
        }

        .text-list-item-content {
          padding: 0 16px;
          min-width: 0;
          font-size: 14px;
          color: @text01;
          flex: 1;
          font-weight: 400;
          line-height: 22px;
          .elliptical-1();

          &.delete {
            text-decoration: line-through;
            opacity: 0.29;
          }
        }

        .text-list-item-index {
          font-size: 14px;
          color: @text01;
          font-weight: 400;
        }

        .label-status {
          color: rgba(186, 187, 190, 1);

          &.marked {
            color: @success;
          }
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    padding: 8px 0;
    width: 100%;
    height: 52px;
    font-size: 14px;
    text-align: center;
    background: #fff;
    box-shadow: 0 -1px 3px rgba(37, 37, 45, 0.2);
    line-height: 36px;

    .deselect-all {
      width: 124px;
      height: 100%;
      color: #009cf8;
      border-right: 1px solid #e8e8eb;

      &:hover {
        cursor: pointer;
      }
    }

    .number-of-selected {
      width: 121px;
      height: 100%;
      color: rgba(16, 16, 20, 0.95);
    }

    .batch-deletion {
      margin-right: 8px;
      width: 88px;
      height: 36px;
      background: #fff;
      border: 1px solid #d9d9db;
      border-radius: 6px;
      box-shadow: 0 2px 0 rgba(0, 0, 0, 0.043);

      &:hover {
        cursor: pointer;
      }
    }
  }

  .index-filter-select-wrap {
    &.ant-select {
      height: 32px;

      :deep(.ant-select-selector) {
        font-size: 14px;
        color: @text01;
        border: 1px solid @border2;
        border-radius: 2px;
        font-weight: 400;
      }
    }
  }
</style>
